define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function() {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'crm/orderck/index' + location.search,
                    add_url: 'crm/orderck/add',
                    edit_url: 'crm/orderck/edit',
                    del_url: 'crm/orderck/del',
                    multi_url: 'crm/orderck/multi',
                    import_url: 'crm/orderck/import',
                    table: 'crm_orderck',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                columns: [
                    [
                        { checkbox: true },
                        { field: 'id', title: __('Id') },
                        { field: 'gongyingshang.name', title: __('Gongyingshang.name'), operate: 'LIKE' },
                        { field: 'admin.nickname', title: __('Admin.nickname'), operate: 'LIKE' },
                        { field: 'images', title: __('Images'), operate: false, events: Table.api.events.image, formatter: Table.api.formatter.images },

                        { field: 'num', title: __('Num') },
                        { field: 'createtime', title: __('Createtime'), operate: 'RANGE', addclass: 'datetimerange', autocomplete: false, formatter: Table.api.formatter.datetime },
                        { field: 'createday', title: __('Createday'), operate: 'RANGE', addclass: 'datetimerange', autocomplete: false },
                        { field: 'createmonth', title: __('Createmonth'), operate: 'LIKE' },
                        { field: 'updatetime', title: __('Updatetime'), operate: 'RANGE', addclass: 'datetimerange', autocomplete: false, formatter: Table.api.formatter.datetime },
                        { field: 'emo', title: __('Emo'), operate: 'LIKE' },
                       
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table,
                            events: {
                                'click .btn-editone': function(e, value, row, index) {
                                    e.stopPropagation();
                                    var url = 'crm/orderck/edit/ids/' + row.id; // 根据你的控制器路径来拼
                                    Fast.api.open(url, '编辑', { area: ['100%', '100%'] });
                                },
                                'click .btn-delone': Table.api.events.operate['click .btn-delone'] // 保留删除按钮
                            },
                            formatter: function(value, row, index) {
                                // 自定义按钮
                                var html = [];
                                html.push('<a href="javascript:;" class="btn btn-xs btn-success btn-editone" title="编辑"><i class="fa fa-pencil"></i></a> ');
                                html.push('<a href="javascript:;" class="btn btn-xs btn-danger btn-delone" title="删除"><i class="fa fa-trash"></i></a>');
                                return html.join('');
                            }
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        index2: function() {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'crm/orderck/index2' + location.search,
                    add_url: 'crm/orderck/add2',
                    edit_url: 'crm/orderck/edit',
                    del_url: 'crm/orderck/del',
                    multi_url: 'crm/orderck/multi',
                    import_url: 'crm/orderck/import',
                    table: 'crm_order',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                columns: [
                    [
                        { checkbox: true },
                        { field: 'id', title: __('Id') },
                        { field: 'gongyingshang.name', title: __('Gongyingshang.name'), operate: 'LIKE' },
                        { field: 'admin.nickname', title: __('Admin.nickname'), operate: 'LIKE' },
                        { field: 'images', title: __('Images'), operate: false, events: Table.api.events.image, formatter: Table.api.formatter.images },

                        { field: 'num', title: __('Num') },
                        { field: 'createtime', title: __('Createtime'), operate: 'RANGE', addclass: 'datetimerange', autocomplete: false, formatter: Table.api.formatter.datetime },
                        { field: 'createday', title: __('Createday'), operate: 'RANGE', addclass: 'datetimerange', autocomplete: false },
                        { field: 'createmonth', title: __('Createmonth'), operate: 'LIKE' },
                        { field: 'updatetime', title: __('Updatetime'), operate: 'RANGE', addclass: 'datetimerange', autocomplete: false, formatter: Table.api.formatter.datetime },
                        { field: 'emo', title: __('Emo'), operate: 'LIKE' },
                       
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table,
                            events: {
                                'click .btn-editone': function(e, value, row, index) {
                                    e.stopPropagation();
                                    var url = 'crm/orderck/edit/ids/' + row.id; // 根据你的控制器路径来拼
                                    Fast.api.open(url, '编辑', { area: ['100%', '100%'] });
                                },
                                'click .btn-delone': Table.api.events.operate['click .btn-delone'] // 保留删除按钮
                            },
                            formatter: function(value, row, index) {
                                // 自定义按钮
                                var html = [];
                                html.push('<a href="javascript:;" class="btn btn-xs btn-success btn-editone" title="编辑"><i class="fa fa-pencil"></i></a> ');
                                html.push('<a href="javascript:;" class="btn btn-xs btn-danger btn-delone" title="删除"><i class="fa fa-trash"></i></a>');
                                return html.join('');
                            }
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function() {
            Controller.api.bindevent();
          
            $(document).on("click", ".btn_del", function() {
                $(this).parent().parent().remove();
            });








            $(document).on("click", ".select_user", function() {
                if ($('#c-kehu_id').val() == '') {
                    Toastr.error("请选择客户");
                    return
                }
                let that = this;
                Fast.api.open('litestore/litestoregoodsspec/choseGoods', '选择商品', {

                    area: ['100%', '100%'],
                    callback(selectData) {
                        let check_user_ids = '';
                        selectData.map(function(item, k) {
                            check_user_ids += check_user_ids ? ',' + item : item;
                        });

                        Fast.api.ajax({
                            url: "/api/index/info",
                            data: { ids: check_user_ids }
                        }, function(res) {

                            var html = "";

                            for (var i = 0; i < res.length; i++) {
                                html = html + '<tr><td><div class="btn_del"><span class="del"><i class="fa fa-trash"></i></span></div></td><td><input type="hidden"name="row[danwei][]"class="danwei"value="' + res[i].danwei + '"><input type="hidden"name="row[goods_spec_id][]"class="goods_code"value="' + res[i].goods_spec_id + '"><input type="hidden"name="row[goods_id][]"class="goods_code"value="' + res[i].goods_id + '"><span>' + res[i].good.goods_name + res[i].spec_name + '</span></td><td><span>' + res[i].danwei + '</span></td><td><input type="number"name="row[item_price][]"class="price"value="' + res[i].goods_price3 + '"></td><td><input type="number"name="row[item_goods_num][]"class="goods_num"value="0"data-price="' + res[i].goods_price3 + '"></td><td><input type="text"name="row[goods_emo][]"class="goods_emo"></td></tr>';
                            }


                            $(".add_item").append(html);



                            return false;
                        }, function() {
                            return false;
                        });



                    }
                });
            });


        },
        add2: function() {
            Controller.api.bindevent();

            $(document).on("click", ".select_user", function() {
                if ($('#c-kehu_id').val() == '') {
                    Toastr.error("请选择客户");
                    return
                }
                let that = this;
                Fast.api.open('litestore/litestoregoodsspec/choseGoods', '选择商品', {

                    area: ['100%', '100%'],
                    callback(selectData) {
                        let check_user_ids = '';
                        selectData.map(function(item, k) {
                            check_user_ids += check_user_ids ? ',' + item : item;
                        });

                        Fast.api.ajax({
                            url: "/api/index/info",
                            data: { ids: check_user_ids }
                        }, function(res) {

                            var html = "";

                            for (var i = 0; i < res.length; i++) {
                                html = html + '<tr><td><div class="btn_del"><span class="del"><i class="fa fa-trash"></i></span></div></td><td><input type="hidden"name="row[danwei][]"class="danwei"value="' + res[i].danwei + '"><input type="hidden"name="row[goods_spec_id][]"class="goods_code"value="' + res[i].goods_spec_id + '"><input type="hidden"name="row[goods_id][]"class="goods_code"value="' + res[i].goods_id + '"><span>' + res[i].good.goods_name + res[i].spec_name + '</span></td><td><span>' + res[i].danwei + '</span></td><td><input type="number"name="row[item_price][]"class="price"value="' + res[i].goods_price3 + '"></td><td><input type="number"name="row[item_goods_num][]"class="goods_num"value="0"data-price="' + res[i].goods_price3 + '"></td><td><input type="text"name="row[goods_emo][]"class="goods_emo"></td></tr>';
                            }


                            $(".add_item").append(html);



                            return false;
                        }, function() {
                            return false;
                        });



                    }
                });
            });


        },
        edit: function() {
            Controller.api.bindevent();
            // $(document).on('focus', '.datetimepicker', function() {
            //   const $this = $(this);
            //   if (!$this.data('DateTimePicker')) { // Eonasdan 插件会保存在 data('DateTimePicker')
            //     $this.datetimepicker({ format: 'YYYY-MM-DD', useCurrent: true });
            //     $this.datetimepicker('show'); // 可选：在 focus 时直接打开选择器
            //   }
            // });

            $(document).on("input", ".price", function() {

                var val = $(this).parent().parent().find('.goods_num').val(); // 转浮点数
                var price = parseFloat($(this).val()); // 转浮点数
                if (val == NaN) {
                    val = 0;
                }
                if (price == NaN) {
                    price = 0;
                }

                var zong_price = val * price;

                zong_price = parseFloat(zong_price).toFixed(2);
                $(this).parent().parent().find('.goods_price').val(zong_price).trigger('input').trigger('change');
                $(this).parent().parent().find('.goods_price2').html(zong_price);
                calculateTotal();




            });


            $(document).on("input", ".youhui_price", function() {

                var price = $(this).parent().parent().find('.price').val(); // 转浮点数
                var num = $(this).parent().parent().find('.goods_num').val(); // 转浮点数
                var val = parseFloat($(this).val()); // 转浮点数

                if (val == NaN) {
                    val = 0;
                }
                if (price == NaN) {
                    price = 0;
                }
                if (num == NaN) {
                    num = 0;
                }

                var zong_price = price * num;



                // console.log(zong_price)
                zong_price = zong_price - val;

                zong_price = parseFloat(zong_price).toFixed(2);

                $(this).parent().parent().find('.goods_price').val(zong_price).trigger('input').trigger('change');;
                $(this).parent().parent().find('.goods_price2').html(zong_price);
                calculateTotal();

            });



            $(document).on("input", ".goods_num", function() {

                var price = parseFloat($(this).attr('data-price')); // 转浮点数
                var val = parseFloat($(this).val()); // 转浮点数
                if (val == NaN) {
                    val = 0;
                }
                if (price == NaN) {
                    price = 0;
                }
                var zong_price = val * price;

                zong_price = parseFloat(zong_price).toFixed(2);
                $(this).parent().parent().find('.goods_price').val(zong_price).trigger('input').trigger('change');;
                $(this).parent().parent().find('.goods_price2').html(zong_price);
                calculateTotal();
                calculateTotal2();


            });


            $(document).on("click", ".btn_del", function() {
                $(this).parent().parent().remove();
            });


            $(document).on("input", ".youhui_price_add", function() {


                calculateTotal();


            });



            // 计算合计的函数
            function calculateTotal() {
                var inputs = document.querySelectorAll('.goods_price');
                var sum = 0;
                var sum2 = 0;
                inputs.forEach(function(input) {
                    sum += parseFloat(input.value) || 0; // 如果输入不是数值，则默认为0
                    sum2 += parseFloat(input.value) || 0; // 如果输入不是数值，则默认为0
                });

                var youhui = $('#c-youhui_price').val();

                if (youhui) {
                    sum2 = sum - parseFloat(youhui);
                }


                $('#c-goods_price').val(sum.toFixed(2));
                $('#c-price').val(sum2.toFixed(2));
            }



            function calculateTotal2() {
                var inputs = document.querySelectorAll('.goods_num');
                var sum = 0;
                inputs.forEach(function(input) {
                    sum += parseFloat(input.value) || 0; // 如果输入不是数值，则默认为0

                });



                $('#c-num').val(sum);

            }



            $(document).on("click", ".select_user", function() {
                if ($('#c-kehu_id').val() == '') {
                    Toastr.error("请选择客户");
                    return
                }
                let that = this;
                Fast.api.open('litestore/litestoregoodsspec/choseGoods', '选择商品', {

                    area: ['100%', '100%'],
                    callback(selectData) {
                        let check_user_ids = '';
                        selectData.map(function(item, k) {
                            check_user_ids += check_user_ids ? ',' + item : item;
                        });

                        Fast.api.ajax({
                            url: "/api/index/info",
                            data: { ids: check_user_ids }
                        }, function(res) {

                            var html = "";

                            for (var i = 0; i < res.length; i++) {
                                html = html + '<tr><td><div class="btn_del"><span class="del"><i class="fa fa-trash"></i></span></div></td><td><input type="hidden" name="row[danwei][]" class="danwei" value="' + res[i].danwei + '"><input type="hidden" name="row[goods_spec_id][]" class="goods_code" value="' + res[i].goods_spec_id + '"><input type="hidden" name="row[goods_id][]" class="goods_code" value="' + res[i].goods_id + '"><span>' + res[i].good.goods_name + res[i].spec_name + '</span></td><td><span>' + res[i].danwei + '</span></td><td><input type="number" name="row[item_price][]" class="price" value="' + res[i].goods_price3 + '"></td><td><input type="number" name="row[item_goods_num][]" class="goods_num" value="0" data-price="' + res[i].goods_price3 + '"></td><td><input class="form-control" type="date" name="row[s_day][]" value=""></td><td><input name="row[b_num][]" type="number" value=""></td><td><input class="form-control" type="date" name="row[e_day][]" value=""></td><td><input type="number" name="row[item_youhui_price][]" class="youhui_price"></td><td><input type="hidden" name="row[item_goods_price][]" class="goods_price"><span class="goods_price2">0</span></td><td><input type="text" name="row[goods_emo][]" class="goods_emo"></td></tr>';
                            }


                            $(".add_item").append(html);



                            return false;
                        }, function() {
                            return false;
                        });



                    }
                });
            });


        },
        api: {
            bindevent: function() {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});